/*
 * @Author: C.
 * @Date: 2023-11-17 16:22:18
 */
import { ref, unref } from 'vue'
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import type { Ref } from 'vue'
import type { FormSchemaItem } from '../../../form/index'
import useMescrollComp from '@/uni_modules/uni-scroll/hooks/useMescrollComp.js'
type IAction = {
  // 刷新
  load: (params?: Recordable) => void
  reLoad: () => void
  setProps: (params: Recordable) => void
  setParams: (params: Recordable) => void
  dataRef: Ref<Recordable[]>
}
type IProps = {
  api: (data: any) => Promise<any>
  params?: Recordable
  top?: string
  formSchema?: FormSchemaItem[]
}
export function useList(
  listProps: IProps
): [register: (obj: Recordable) => void, action: IAction] {
  const { mescrollItem } = useMescrollComp(onPageScroll, onReachBottom)

  const actionRef = ref<Recordable>({})
  const dataRef = ref([])
  function setData(data: any) {
    dataRef.value = data
  }
  function register(action: any) {
    if (action.type == 'mounted') {
      actionRef.value = action
      action.setProps({
        ...unref(listProps),
      })
      if (listProps.params) {
        action.initParams(listProps.params)
      }
      mescrollItem.value = action
    } else {
      setData(unref(action))
    }
  }
  const Action = {
    // 刷新
    load: (params = {}) => {
      unref(actionRef).load(params)
    },
    // 重置刷新
    reLoad: () => {
      unref(actionRef).reLoad()
    },
    // 设置组件参数
    setProps: (props: Recordable) => {
      unref(actionRef).setProps(props)
    },
    // 设置接口参数
    setParams: (params: Recordable) => {
      unref(actionRef).setParams(params)
    },
    dataRef,
    mescrollItem,
  }
  return [register, Action]
}
